use crate::Message;
use iced::{text_input, Button, Column, Container, Radio, Row, Text, TextInput};

pub struct FeedPlot {
    pub start_state: text_input::State,
    pub end_state: text_input::State,
    pub duration_state: text_input::State,
    pub start: String,
    pub end: String,
    pub duration: String,
    pub machine_idx: usize,
    pub use_fastfeed: bool,
    pub mear_idx: usize,
    pub symbol_state: text_input::State,
    pub symbol: String,
    pub symbols: Vec<String>,
    pub symbol_add_state: iced::button::State,
    pub symbols_clear: iced::button::State,
    pub copy_coin1_state: iced::button::State,
    pub copy_coin2_state: iced::button::State,
}

impl Default for FeedPlot {
    fn default() -> Self {
        Self {
            machine_idx: 16,
            start_state: Default::default(),
            end_state: Default::default(),
            duration_state: Default::default(),
            start: Default::default(),
            end: Default::default(),
            duration: Default::default(),
            use_fastfeed: true,
            mear_idx: 0,
            symbol_state: Default::default(),
            symbol: Default::default(),
            symbols: Default::default(),
            symbol_add_state: Default::default(),
            symbols_clear: Default::default(),
            copy_coin1_state: Default::default(),
            copy_coin2_state: Default::default(),
        }
    }
}

const FEED_MACHINES: [&'static str; 22] = [
    "feed-01.ap-northeast-1.aws",
    "feed-01.ap-northeast-1.aws.huobi",
    "feed-01.ap-northeast-2.aws",
    "feed-01.cn-hongkong.aliyun",
    "feed-01.cn-hongkong.aliyun.okex",
    "feed-01.eu-west-1.aws",
    "feed-01.us-east-1.aws",
    "feed-02.ap-northeast-1.aws",
    "feed-02.ap-northeast-2.aws",
    "feed-02.cn-hongkong.aliyun",
    "feed-02.eu-west-1.aws",
    "feed-02.us-east-1.aws",
    "feed-03.ap-northeast-1.aws",
    "feed-03.cn-hongkong.aliyun",
    "feed-04.ap-northeast-1.aws",
    "feed-04.cn-hongkong.aliyun",
    "feed-05.ap-northeast-1.aws",
    "feed-05.ap-northeast-1.aws.deprecated",
    "feed-05.cn-hongkong.aliyun",
    "feed-05.cn-hongkong.aliyun.deprecated",
    "feed-06.ap-northeast-1.aws",
    "feed-06.cn-hongkong.aliyun",
];

const MEARS: [&'static str; 35] = [
    "Futures.Binance.v1.l1_realtime",
    "Futures.Binance.v1.realtime",
    "Futures.Binance.v1.realtime_light_bbo",
    "Futures.Binance.v1.snapshot",
    "Futures.Bitflyer.v1.realtime",
    "Futures.Bitmex.v1.realtime",
    "Futures.Bitmex.v1.realtime_light_bbo",
    "Futures.Bybit.v2-linear.realtime",
    "Futures.Bybit.v2.realtime",
    "Futures.Ftx.v1.realtime",
    "Futures.Huobi.v1-swap.incremental",
    "Futures.Huobi.v1-swap.realtime_light_bbo",
    "Futures.Huobi.v1-swap.snapshot",
    "Futures.Huobi.v1.incremental",
    "Futures.Huobi.v1.realtime_light_bbo",
    "Futures.Huobi.v1.snapshot",
    "Futures.Okex.v3-swap.realtime",
    "Futures.Okex.v3-swap.realtime_light_bbo",
    "Futures.Okex.v3-swap.snapshot",
    "Futures.Okex.v3.realtime",
    "Futures.Okex.v3.realtime_light_bbo",
    "Futures.Okex.v3.snapshot",
    "Spot.Binance.v1.l1_realtime",
    "Spot.Binance.v1.snapshot",
    "Spot.Bithumb.v2.realtime",
    "Spot.Bitstamp.v2.snapshot",
    "Spot.Coinone.v2.realtime",
    "Spot.Ftx.v1.realtime",
    "Spot.Gdax.v1.snapshot",
    "Spot.Huobi.v1.snapshot",
    "Spot.Kraken.v1.snapshot",
    "Spot.Okex.v3.realtime",
    "Spot.Okex.v3.snapshot",
    "Spot.Quoinex.v2.realtime",
    "Spot.Upbit.v1.realtime",
];

impl FeedPlot {
    pub fn view(&mut self) -> Column<Message> {
        let mut machine_list = Column::new();
        for (i, m) in FEED_MACHINES.iter().enumerate() {
            machine_list = machine_list.push(Container::new(Radio::new(
                i,
                m.clone(),
                Some(self.machine_idx),
                |idx| Message::FeedPlotMachine(idx),
            )));
        }
        let mut mear_list = Column::new();
        for (i, m) in MEARS.iter().enumerate() {
            mear_list = mear_list.push(Container::new(Radio::new(
                i,
                m.clone(),
                Some(self.mear_idx),
                |idx| Message::FeedPlotMear(idx),
            )));
        }
        let mut symbols = Column::new();
        symbols = symbols.push(
            Row::new()
                .push(
                    TextInput::new(
                        &mut self.symbol_state,
                        "BTC-USD.QUARTER",
                        &self.symbol,
                        |v| Message::FeedPlotSymbol(v),
                    )
                    .width(iced::Length::Units(200)),
                )
                .push(
                    Button::new(&mut self.symbol_add_state, Text::new("Add"))
                        .on_press(Message::FeedPlotSymbolAdd),
                ),
        );
        for symbol in &self.symbols {
            symbols = symbols.push(Text::new(symbol));
        }
        symbols = symbols.push(
            Button::new(&mut self.symbols_clear, Text::new("Clear All"))
                .on_press(Message::FeedPlotSymbolsClear),
        );

        let mut results = Column::new().spacing(50);
        let coin1_cmd = format!("./pyrunner python/coin/strategy/mm/tool/feed_archive_checker.py --worker_ids=0 --use_feed_cache={} --feed_machine={} --api_override=Futures:Okex=v3.realtime,Futures:Binance=v1.l1_realtime,Futures:Huobi=v1.incremental,Futures:Bitmex=v1.realtime", if self.use_fastfeed { "True" } else { "False" }, FEED_MACHINES[self.machine_idx]);
        results = results.push(Row::new().spacing(50).push(Text::new("Coin1").size(30)).push(
            Button::new(&mut self.copy_coin1_state, Text::new("copy")).on_press(Message::ClipboardCopy(coin1_cmd.clone()))
        ));
        results = results.push(Text::new(coin1_cmd));
        // ./pyrunner python/coin/strategy/mm/tool/feed_archive_checker.py --trading_date=20200527 --feed_machine=feed-best.ap-northeast-1.aws --subsymbols=Binance:Futures:BTC-USDT.PERPETUAL --api_override=Futures:Binance=v1.realtime_light_bbo --time_range=0-2
        let dot = MEARS[self.mear_idx].rfind(".").unwrap();
        let (mea, recipe) = (&MEARS[self.mear_idx][..dot], &MEARS[self.mear_idx][dot+1..]);
        let coin2_cmd = loop {
            if self.symbols.is_empty() {
                break "Provide symbol".to_string();
            }
            if (self.start.is_empty() as u8) + (self.end.is_empty() as u8) + (self.duration.is_empty() as u8) != 1 {
                break "Provide exactly 2 of start, end, duartion".to_string();
            }

            break format!(
                "bazel build --config opt //cc/appcoin2/support/feed:plot
    ./bazel-bin/cc/appcoin2/support/feed/plot --{} --machine {} --mea {} --recipe {} --product {}{}{}{}",
                if self.use_fastfeed { "fastfeed" } else { "raw" },
                FEED_MACHINES[self.machine_idx],
                mea,
                recipe,
                self.symbols.join(" --product "),
                if self.start.is_empty() { "".to_string() } else {format!(" --start {}", self.start)},
                if self.end.is_empty() { "".to_string() } else {format!(" --end {}", self.end)},
                if self.duration.is_empty() { "".to_string() } else {format!(" --duration {}", self.duration)},
            );
        };
        results = results.push(Row::new().spacing(50).push(Text::new("Coin2").size(30)).push(
            Button::new(&mut self.copy_coin2_state, Text::new("copy")).on_press(Message::ClipboardCopy(coin2_cmd.clone()))
        ));
        results = results.push(Text::new(coin2_cmd));

        Column::new()
            .spacing(20)
            .push(
                Row::new()
                    .spacing(20)
                    .push(Text::new("start"))
                    .push(TextInput::new(
                        &mut self.start_state,
                        "YYYY-MM-DD",
                        &self.start,
                        |v| Message::FeedPlotStart(v),
                    )),
            )
            .push(
                Row::new()
                    .spacing(20)
                    .push(Text::new("duration"))
                    .push(TextInput::new(
                        &mut self.duration_state,
                        "PT1H",
                        &self.duration,
                        |v| Message::FeedPlotDuration(v),
                    )),
            )
            .push(
                Row::new()
                    .spacing(20)
                    .push(Text::new("end"))
                    .push(TextInput::new(
                        &mut self.end_state,
                        "YYYY-MM-DD",
                        &self.end,
                        |v| Message::FeedPlotEnd(v),
                    )),
            )
            .push(
                Row::new()
                    .spacing(20)
                    .push(Container::new(Radio::new(
                        true,
                        "FastFeed",
                        Some(self.use_fastfeed),
                        |v| Message::FeedPlotFastFeed(v),
                    )))
                    .push(Radio::new(false, "Raw", Some(self.use_fastfeed), |v| {
                        Message::FeedPlotFastFeed(v)
                    })),
            )
            .push(
                Row::new()
                    .spacing(20)
                    .push(Text::new("feed machine"))
                    .push(machine_list)
                    .push(Text::new("m.e.a.r"))
                    .push(mear_list)
                    .push(Text::new("symbols"))
                    .push(symbols)
                    .push(results),
            )
            .into()
    }
}

